import { getRegPhoneCode, login } from '@/api/user'
import { setUser, removeUser, getUser } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return getUser()
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, type, id, code } = userInfo
    return new Promise((resolve, reject) => {
      const data = { 'principal': username.trim(), type }
      if (type === 'PhoneCode') {
        data.code = code
        data.id = id
      } else {
        data.credentials = password
      }
      login(data).then(response => {
        const { data: { token, name, avatar }} = response
        commit('SET_TOKEN', token)
        commit('SET_NAME', name)
        const t = avatar !== '' ? avatar : ('https://ui-avatars.com/api/?name=' + name)
        commit('SET_AVATAR', t)
        setUser({ token, name, 'avatar': t })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // login phone code
  loginPhoneCode({ commit }, phone) {
    return new Promise((resolve, reject) => {
      getRegPhoneCode({ phone }).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeUser() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
      // logout(state.token).then(() => {
      //   removeToken() // must remove  token  first
      //   resetRouter()
      //   commit('RESET_STATE')
      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeUser() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

